package com.serookie.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.serookie.entity.GoodsCategory;
import com.serookie.mapper.GoodsCategoryMapper;
import com.serookie.service.GoodsCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author kevintam
 * @version 1.0
 * @date 2021/5/8 15:31
 */
@Service
public class GoodsCategoryServiceImpl extends ServiceImpl<GoodsCategoryMapper, GoodsCategory> implements GoodsCategoryService{

    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;


    @Override
    public List<GoodsCategory> getTypeWithTree() {
//        第一步查询所有分类
        List<GoodsCategory> all = goodsCategoryMapper.selectList(null);
//        找到所有的一级目录
        List<GoodsCategory> collect = all.stream()
                .filter(GoodsType -> GoodsType.getParentCid() .equals(0))
                .map((menu)->{
                    menu.setGoodsTypeList(allTree(menu,all));
                    return menu;
                }).sorted((menu1,menu2)->{
                    return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());
        return collect;
    }
//   删除商品分类
    @Override
    public void removeByIds(List<Integer> asList) {
        //TODO
         goodsCategoryMapper.deleteBatchIds(asList);
    }

    //    递归查找所有的子菜单
    private List<GoodsCategory> allTree(GoodsCategory root,List<GoodsCategory> all){
        List<GoodsCategory> categories = all.stream().filter(goodsCategory -> {
            return goodsCategory.getParentCid().equals(root.getCatId());
        }).map(goodsCategory->{
            goodsCategory.setGoodsTypeList(allTree(goodsCategory,all));
            return goodsCategory;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return categories;
    }

    /**
     * 新增分类
     * @param entity
     * @return
     */
    @Override
    public boolean save(GoodsCategory entity) {
        int insert = goodsCategoryMapper.insert(entity);
        return insert>0;
    }

    @Override
    public boolean updateById(GoodsCategory entity) {
        int byId = goodsCategoryMapper.updateById(entity);
        return byId>0;
    }

    @Override
    public GoodsCategory getById(Integer id) {
        return goodsCategoryMapper.selectById(id);
    }

    @Override
    public Integer goodsCount() {
        return goodsCategoryMapper.selectCount(null);
    }
}
